from decimal import Decimal as D
from django.template.loader import render_to_string
import math
import settings

from oscar.apps.shipping import base

class OCA(base.ShippingMethod):
    code = 'oca-shipping'
    name = 'Envio por OCA'

    def set_user(self, user):
        self.user = user

    def basket_charge_incl_tax(self):
        user_region = self.basket.owner.get_profile().region
        weight = 0.0
        for line in self.basket.all_lines():
            weight += line.product.peso() * line.quantity

        print weight
        price_range = 0
        is_extra_weight = True
        for x in settings.OCA_RANGES:
            if weight <= x:
                is_extra_weight = False
                break
            price_range += 1

        extra_price = 0
        if is_extra_weight:
            price_range -= 1
            extra_weight = math.ceil(weight - settings.OCA_RANGES[-1])
            extra_price = settings.OCA_EXTRAS[user_region] * extra_weight

        ocaZone = settings.OCA_ZONES[user_region]
        shipping_price = ocaZone[price_range] + extra_price
        shipping_price *= 1.21

        return D(shipping_price)

    def basket_charge_excl_tax(self):
        return 250

class Standard(base.ShippingMethod):
    code = 'standard'
    name = 'Standard shipping'
    description = render_to_string('shipping/standard.html')

    def basket_charge_incl_tax(self):
        # Free for orders over some threshold
        if self.basket.total_incl_tax > D('12.00'):
            return D('0.00')

        # Simple method - charge 0.99 per item
        total = D('0.00')
        charge_per_item = D('0.99')
        for line in self.basket.all_lines():
            total += line.quantity * charge_per_item
        return total

    def basket_charge_excl_tax(self):
        # Assume no tax
        return self.basket_charge_incl_tax()


class Express(base.ShippingMethod):
    code = 'express'
    name = 'Express shipping'
    description = render_to_string('shipping/express.html')

    def basket_charge_incl_tax(self):
        # Simple method - charge 0.99 per item
        total = D('0.00')
        charge_per_item = D('1.50')
        for line in self.basket.all_lines():
            total += line.quantity * charge_per_item
        return total

    def basket_charge_excl_tax(self):
        # Assume no tax
        return self.basket_charge_incl_tax()
